var facetters = new Array();
var prevSelElement;
var userClicksTime = new Object();
var userClicks = new Object();
	
	function encodeURLnonASCII(url) {
		if (url == null) return "";
		sb = "";
		for (var i = 0; i < url.length; i++) 
		{ 
			c = url.charAt(i); 
			if (c >= ' ' && c <= '~') sb = sb+c; 
			else sb = sb+escape(c);
		} 
		return sb; 
	};

	function buildIdURL(url) {
		var uri = new Uri(url);
		if (uri.protocol()==uriHere.protocol()
				&& uri.host()==uriHere.host()
				&& uri.port()==uriHere.port()){ // same origin: service can remain unchanged
			uri.setHost("");
			uri.setPort("");
			uri.setProtocol("");
		}
		return encodeURLnonASCII(encodeURIComponent(unescape(uri.toString().replace('+',' '))));
	}
		
	function popupImage( elem, img, idInnerRecord ) 
    { 
		recClick(idInnerRecord);
    	var fg = $(elem).children('span');
    	if ( ! fg.hasClass('popup_foreground')) {
	        fg.addClass ("popup_foreground"); 
	        var container = $( '<span class="popup_foreground_container"></span>' );
	        var image = $( "<img class='image_full popup_image' src='"+img+"' />" ); 
	        fg.append( container ); 
	        container.append( image ); 
	     
	        fg.click(function(event){
	            $(this).removeClass("popup_foreground"); 
	        	$(this).empty();
	        }); 
    	}
    } 

    function stringAttribute (input) {
    	input = input.replace(/\\/g,"\\\\");
    	input = input.replace(/\'/g,"\\'");
    	input = input.replace(/&/g,"&amp;");
    	input = input.replace(/\"/g,"&quot;");
    	input = input.replace(/</g,"&lt;");
    	input = input.replace(/>/g,"&gt;");
    	return input;
    }
/*
    function noHide(elem) {
		parent = $(elem.parentElement.parentElement).removeClass('itemtabs');    	
    }
*/
	function noHideAll(elem,idInner) {
      var thisFacetter = facetters[idInner];
      if (thisFacetter && thisFacetter.settings.state.orderBy == "showHide") {
		thisFacetter.settings.state.orderBy = "noSort";
  	    $(thisFacetter.settings.facetSelector).trigger("facetedsearchorderby", "noSort");
	    thisFacetter.settings.state.shownResults = 0;
	    thisFacetter.order();
	    thisFacetter.updateResults();
      } 
	  $('[id*="'+idInner+'-"] > .itemtabs').each(function(){
			$(this).removeClass("itemtabs");
		  });
	  if (elem) $(elem).hide();
	}

	function recClick (idInnerRecord) {
		if (idInnerRecord) {
			if ($('#'+idInnerRecord+'-rec').length <= 0) {
				alert ('#'+idInnerRecord+"-rec do no exist!");
			} else {
				if (userClicks && userClicks[idInnerRecord]) {
					delete userClicksTime[userClicks[idInnerRecord]];
				}
				var timestamp = new Date().getTime();
				userClicksTime[timestamp] = idInnerRecord;
				userClicks[idInnerRecord] = timestamp;
			}
		}
	}

	function lastclicks () {
		var popupHtml = "<ul>";
		for (var times in userClicksTime) {
			var ids = userClicksTime[times];
			var stillThere = $('#'+ids+'-rec');
			if (stillThere.length == 0) {
				//delete userClicks[ids];  IF USER RE-OPENS A SUB-RESULT, HE MAY BE INTERESTED TO KNOW WHERE HE HAD BEEN IN THERE
				//delete userClicksTime[times];  BUT THE TITLE IS INNACCESSIBLE!!!
			} else {
				stillThere.each(function(){
					popupHtml+='<li><a href="#'+ids+'-rec" onclick="javascript:$(\'#breadcrumbs\').dialog(\'close\');">'+this.firstChild.innerHTML+'</a></li>';			
				});
			}
		}
		popupHtml += '</ul><p align="center"><a href="#" onclick="javascript:$(\'#breadcrumbs\').dialog(\'close\');return false;"><i>Click to scroll back to one of these records (or here to close).</i></a></p>';

    	var fg = $('#breadcrumbs');
    	fg.html(popupHtml);
    	fg.dialog({ closeText:'Close', modal:false, title:'Your clicks in this page:', minWidth:350, minHeight:350, position:['right','bottom']  });
	}

	function checkBasketName (json) {
   		if (json.basketname && currentbasket != json.basketname) {
   			alert("Current basket is changed to "+json.basketname+"\nRefresh page!");
   			currentbasket = json.basketname;	   				
   		}
		return currentbasket;
	}
	
	function displayOpenLink(elem,encodedurl,application,idInnerRecord) {
		recClick(idInnerRecord);
		window.open(encodedurl,application).focus();
		/*
		var url = '/scheme/recevent.jsp?url='+encodedurl+'&type=DISPLAY';
	   	var jsonClient = new AtomClient(url);
	   	jsonClient.json('', function completeResult( json ) {
	   		checkBasketName(json);
	   	}) ;
	   	*/	
	}

	function editOpenLink(elem,encodedurl,application,idInnerRecord) {
		recClick(idInnerRecord);
		window.open(encodedurl,application).focus();
	}

	function sourceOpenLink(elem,encodedurl,application,idInnerRecord) {
		recClick(idInnerRecord);
		window.open(encodedurl).focus();
	}

	function viewManage(elem,encodedurl,idInner,tag) {
		if (!tag) tag = "mark_v";
		var url = '/scheme/settag.jsp?url='+encodedurl+'&tag='+tag;
		var pSoul = tag.indexOf('_');
		var scheme = 'free';
		if (pSoul >= 0) {
			scheme = tag.substring(0,pSoul);
			tag = tag.substring(pSoul+1);
		}
		var indexEntries = facetters[idInner].settings.indexEntries;
		var anEntry = indexEntries[encodedurl];
		if (anEntry != null) {
			recClick(idInner+'-'+anEntry.apprecord);
			if (anEntry[scheme] && (_.find(anEntry[scheme],function(current){return current==tag;})) ) {
				url += '&remove=on';
			}
			//alert (url);
			var jsonClient = new AtomClient(url);
			jsonClient.json('', function completeResult( json ) {
				//alert(appli+'/'+record+':'+json.status);
				if (json.status == 'set') {
					$(elem).children('img')[0].src = '/scheme/image/16x16/check.png';
					if (!anEntry[scheme]) anEntry[scheme] = new Array();
					anEntry[scheme][anEntry[scheme].length] = tag; 
				} else {
					$(elem).children('img')[0].src = '/scheme/image/16x16/uncheck.png';
					anEntry[scheme] = _.filter(anEntry[scheme],function(current){return current!=tag;});
				}
				$('#sizeView').text(json.size);
			}) ;	
		}
	}

	function basketManage(elem,encodedurl,idInner,tag) {
		if (!tag) tag = "mark_basket";
		var url = '/scheme/settag.jsp?url='+encodedurl+'&tag='+tag;
		var pSoul = tag.indexOf('_');
		var scheme = 'free';
		if (pSoul >= 0) {
			scheme = tag.substring(0,pSoul);
			tag = tag.substring(pSoul+1);
		}
		var indexEntries = facetters[idInner].settings.indexEntries;
		var anEntry = indexEntries[encodedurl];
		if (anEntry != null) {
			recClick(idInner+'-'+anEntry.apprecord);
			if (anEntry[scheme] && (_.find(anEntry[scheme],function(current){return current==tag;})) ) {
				url += '&remove=on';
			} else {
				var title = $('a[href="'+encodedurl+'"][target="_blank"]').text();
				url += '&title='+escape(title);
			}
			//alert (url);
			var jsonClient = new AtomClient(url);
			jsonClient.json('', function completeResult( json ) {
				//alert(appli+'/'+record+':'+json.status);
				if (json.status == 'set') {
					$(elem).children('img')[0].src = '/scheme/image/inbasket.gif';
					if (!anEntry[scheme]) anEntry[scheme] = new Array();
					anEntry[scheme][anEntry[scheme].length] = tag; 
				} else {
					$(elem).children('img')[0].src = '/scheme/image/outbasket.gif';
					anEntry[scheme] = _.filter(anEntry[scheme],function(current){return current!=tag;});
				}
				$('#sizeBasket').text(json.size);
			}) ;	
		}
	}

	function commentManage(elem,encodedurl,idInner,comment) {
		if (!comment) comment = prompt("Please enter your comment","");
		var url = '/scheme/setcomment.jsp?url='+encodedurl+'&comment='+encodeURIComponent(comment);
		if (!comment) url += '&remove=on';
		var indexEntries = facetters[idInner].settings.indexEntries;
		var anEntry = indexEntries[encodedurl];
		if (anEntry != null) {
			recClick(idInner+'-'+anEntry.apprecord);
			var jsonClient = new AtomClient(url);
			jsonClient.json('', function completeResult( json ) {
				anEntry.comments = _.filter(anEntry.comments,function(current){return current.user!=json.user;});
				if (json.action == 'added') {
					alert ('New comment recorded');
					anEntry.comments[anEntry.comments.length] = json;
				} else if (json.action == 'updated') {
					alert ('Comment modified');
					anEntry.comments[anEntry.comments.length] = json;
				} else if (json.action == 'removed') {
					alert ('Comment removed');
				}
			}) ;	
		}
	}

    function entryDisplay (obj, idInner, level, lonely) {
    	var idLink = idInner + '-' + obj.apprecord;
    	var result = "";
    	var enclosure = obj.getLinkObject("enclosure");
		var thumb = obj.getLink("thumbnail");
    	if (obj.year || enclosure || thumb ) {
        	result += '<p class=\"date\">';
        	if (obj.year && obj.year.label > '0000') {
        		result += obj.year.label;
        		if (obj.month) result += '/'+obj.month;
        	}
   			if (thumb != null) {
	   			result += '<img src=\"'+thumb+'" class="thumbnail"/>';
	   		}
        	if (enclosure) {
        		var typeEnc = enclosure.getType();
        		if (typeEnc && typeEnc.indexOf('image/')>=0) {
	        		result += '<span onmouseover="javascript:popupImage(this,\''+enclosure.getHRef().getValue()+'\',\''+idLink+'\')" class="enclosurelink"><span></span><img src="/scheme/image/mime/'+typeEnc+'.gif" border="0"/>'+'</span>';
        		} else {
        			result += '<a href="#" onclick="javascript:displayOpenLink(this,\''+enclosure.getHRef().getValue()+'\',\''+obj.application+'\',\''+idLink+'\');return false" title="'+enclosure.getTitle()+'" class="enclosurelink"><img src="/scheme/image/mime/'+typeEnc+'.gif" border="0""/>'+'</a>';
        		}
       		}
        	result += '</p>';    		
    	}
    	
    	result += '<h4><a name=\"' + idLink + '"></a><span id="'+idLink+'-rec">' + obj.label + '</span></h4>';  // THIS THE ADDRESS OF THE ENTRY TITLE! 
        if (obj.authors) {
        	result += '<ul class=\"authors\">';
        	for (var jcat = 0; jcat < obj.authors.length; jcat++) {
        		var currName = obj.authors[jcat].name;
        		if (obj.authors[jcat].uri) {
        			currName = '<a href="#'+idLink+'\" onclick="javascript:openInner(this,\''+idLink+'\',\''+obj.authors[jcat].uri+'\','+level+',\''+idLink+'\')">'+currName+'</a>';
        		}
        		result += '<li>' + currName + '&thinsp;;</li>';
        	}
        	result += '</ul>';
        }
    	if (obj.summary) {
    		result += '<p class=\"desc\">' +  obj.getSummary().content + '</p>';
    	} else if (obj.content && obj.content.getType().indexOf('html')>=0) {
    		result += '<p class=\"desc\">' +  obj.getContent().content + '</p>';
    	} 

    	result += '<div id=\"'+idLink +'tabs\" class=\"subitemtabs' + ( level > 0 ? (' lev' + (level-1) ) : '' ) + '\"><ul'+(lonely?'':(' class=\"itemtabs\" onmouseover=\"javascript:$(this).removeClass(\'itemtabs\')\"'))+'>';
    	var inOut = _.find(obj['mark'],function(tag){return tag.term=='basket';});
    	result += '<li class="ui-state-default ui-corner-top" id="'+idLink +'first" class=\"subitemonetab\"><a href="#" onclick="javascript:basketManage(this,\''+buildIdURL(obj.getLink("alternate"))+'\',\''+idInner+'\');return false" title="basket"><img src="image/'+(inOut?'in':'out')+'basket.gif" border=0 title="Selection basket"/></a></li>';
    	var tagSize = '';
    	var viewed = false;
    	if (obj.tag && obj.tag.length > 0) {
    		tagSize = obj.tag.length;
   			for (var jcat = 0; jcat < obj.tag.length; jcat++) {
   				var categ = obj.tag[jcat];
   				if (categ.term == 'v' && categ.content == '*') { // Own view tag!
   					viewed = true;
   					tagSize--;
   					break;
   				}
   			}
   			if (tagSize) tagSize = ':'+tagSize;
   			else tagSize = '';
    	}
    	viewed = _.find(obj['mark'],function(tag){return tag.term=='v';});
		result += '<li><a href="#'+idLink +'tabs-viewed" title="viewed" style="text-decoration:line-through" onclick="javascript:viewManage(this,\''+buildIdURL(obj.getLink("alternate"))+'\',\''+idInner+'\');return false;"><img src="image/16x16/'+(viewed?'':'un')+'check.png" border=0 alt="viewed"/></a></li>';
    	result += '<li><a href="#'+idLink +'tabs-tag" title="tag"><img src="image/16x16/tag.png" border=0 alt="tag"/>' + tagSize + '</a></li>';
    	var commentSize = '';
    	if (obj.comments && obj.comments.length > 0) {
    		commentSize = ':'+obj.comments.length;
    	}
    	result += '<li><a href="#'+idLink +'tabs-comment" title="comment"><img src="image/16x16/comment.png" border=0 alt="comment"/>' + commentSize + '</a></li>';
    	if (obj.facets) {
	    	for (var icat in obj.facets) {
	    		if (icat == 'tag') continue;
	    		if (obj[icat].length > 0) {
	    			result += '<li><a href="#'+idLink +'tabs-' + icat + '" title="'+icat+'">' + obj.facets[icat] + obj[icat].length +'</a></li>';
				}
	    	}
    	}
    	if (obj.relation) {
    		for (var jcat = 0; jcat < obj.relation.length; jcat++) {
    			result += '<li class="ui-state-default ui-corner-top">' + obj.relation[jcat] + '</li>';
    			// ui-tabs-selected ui-state-active
    		}
    	}
    	if (obj.sourceLink) {
	    	result += '<li class="ui-state-default ui-corner-top"  id="'+idLink +'source"><a href="#" onclick="javascript:sourceOpenLink(this,\''+obj.sourceLink.getHRef().getValue()+'\',\''+obj.application+'\',\''+idLink+'\');return false;" title="'+stringAttribute(obj.sourceLink.getTitle())+'"><img src="image/16x16/publish.png" border=0 title="'+stringAttribute(obj.sourceLink.getTitle())+'"/></a></li>';
    	}
    	if (obj.editLink) {
	    	result += '<li class="ui-state-default ui-corner-top"  id="'+idLink +'edit"><a href="#" onclick="javascript:editOpenLink(this,\''+obj.editLink+'\',\''+obj.application+'\',\''+idLink+'\');return false;" title="edit"><img src="image/16x16/edit.png" border=0 alt="edit"/></a></li>';
    	}
    	result += '</ul>';
		result += '<div id=\"'+idLink +'tabs-comment\">';
		if (obj.comments) {
			for (var jcat = 0; jcat < obj.comments.length; jcat++) {
				var comment = obj.comments[jcat];
				result += ('<li>'+comment.time.substring(0,16)+': <b>'+comment.comment+'</b> ('+comment.user+')</li>');
			}
		}
		result += ('<li><a href="#" onclick="javascript:commentManage(this,\''+buildIdURL(obj.getLink("alternate"))+'\',\''+idInner+'\')";return=false;">Add or update your comment!</a></li>');
		result += '</div>';
		var sublinking = false;
    	if (obj.facets) {
	    	for (var icat in obj.facets) {
	    		if (obj[icat].length > 0) {
	    			result += '<div id=\"'+idLink +'tabs-' + icat + '\"><ul class="itemFacets">';
	    			for (var jcat = 0; jcat < obj[icat].length; jcat++) {
	    				var categ = obj[icat][jcat];
	    				var lab = categ.content;
	    				if (!lab || lab == '1') {
	    					lab = "";
	    				} else if (lab == '*') {
	    					if (categ.term == 'v') continue;
	    					else lab = '<a href="#" class="removelinks">x</a>';
	    				} else {
	    					lab = ': '+lab;
	    				}
	    				if ( categ.term // (/^\w+$/.test(categ.term))
	    						&& categ.scheme
	    						&& ( ArrayIndexOf(schemeNames.skosView.narrower, function(obj) { return obj.about == categ.scheme; }) >= 0)) {
		    				result += '<li class="linkedcateg"><a class="linkedcateg" href="#'+idLink+'_categ\" onclick="javascript:openInner(this,\''+idLink+'_categ\',\'/scheme/concept.svc/'+categ.scheme+'('+categ.term+')\','+level+',\''+idLink+'\')">'+categ.label+'</a>'+lab+'</li>';
		    				sublinking = true;
	    				} else {
		    				result += '<li class="unlinkedcateg">'+categ.label+lab+'</li>';
	    				}
	    			}
	    			result += '</ul></div>';
				}
	    	}
    	}
    	result += '<div id="'+idLink+'" class=\"iteminnerset\"></div>';
    	if (sublinking) {
        	result += '<div id="'+idLink+'_categ" class=\"iteminnerset\"></div>';
    	}
    	result += '</div>';
    	return result;
    }

    
    var rssBack = null;

    function dumpFeed() {
    	if (rssBack != null) {
    		alert(rssBack);
    	}
    }
    
    function insertFeed(service,idInner,level,closed) {
		$('#'+idInner).html('<div id=\"'+idInner+'feedLabel\" class="feedLabel">Waiting for feed '+service+'</div><div id=\"'+idInner+'facets\" class="yellow">... ... ...</div><div id=\"'+idInner+'bottom\">... ... ...</div><div id=\"'+idInner+'results\">Waiting for results to display...</div>');
		var uri = new Uri(service);
		if ((uri.protocol()==uriHere.protocol()
			&& uri.host()==uriHere.host()
			&& uri.port()==uriHere.port())
			||(uri.protocol()==''&&uri.host()==''&&uri.port()=='')){ // same origin: service can remain unchanged
		} else { // redirect through the proxy
			uri.setPath('/proxy/'+uri.host()+uri.path());
			uri.setHost(uriHere.host());
			uri.setPort(uriHere.port());
			uri.setProtocol(uriHere.protocol());
		}
		var serviceURL = uri.toString();
		// alert (service);
	   	var atomClient = new AtomClient(serviceURL);
	   	atomClient.service = findApplication(serviceURL);
	   	atomClient.securityToken = appKeys[atomClient.service];
	   	atomClient.app = findApp(atomClient.service);
	   	atomClient.get(function writeResult(xmlDocument, txtDocument) {
	   					rssBack = txtDocument;
				   		var isPubMed = atomClient.service=="pubmed";
	   					var feed = new Feed(xmlDocument, isPubMed); //feed.readFromNode(xmlDocument);
				   		if (isPubMed) {
				   			feed.setTitle(new Text(unescape(uri.getQueryParamValue("term")),"text"));
				   		}
				   		var entries = feed.getEntries();
				   		var feedSize = entries.length;
				   		feed.label = '<a name="top'+idInner+'"></a>';
				   		var defaultIcon = "";
				   		if (atomClient.app) {
				   			defaultIcon = atomClient.app.icon;
				   			if (defaultIcon) feed.label += '<img border="0" height="18" src="'+defaultIcon+'" alt="'+atomClient.service+'"/>';
				   		}

				   		if (feedSize > 1) {
					   		var navlinks = '<span class="setnav">';
					   		var nolinks = true;
					   		var altern = feed.getLink("first"); 
				   			if (altern != null) {
				   				navlinks += '<a href="#" onclick="javascript:insertFeed(\''+altern+'\',\''+idInner+'\','+level+');return false;"><img src="image/first.gif" border=0/></a>';
				   				nolinks = false;
					   		}
				   			var altern = feed.getLink("prev"); 
				   			if (altern==null) altern = feed.getLink("previous"); 
				   			if (altern != null) {
				   				navlinks += '<a href="#" onclick="javascript:insertFeed(\''+altern+'\',\''+idInner+'\','+level+');return false;"><img src="image/previous.gif" border=0/></a>';
				   				nolinks = false;
					   		}
				   			navlinks += '<small>'+feed.getStartIndex()+'-'+(feed.getStartIndex()+feedSize-1)+'</small>';
				   			var altern = feed.getLink("next"); 
				   			if (altern != null) {
				   				navlinks += '<a href="#" onclick="javascript:insertFeed(\''+altern+'\',\''+idInner+'\','+level+');return false;"><img src="image/next.gif" border=0/></a>';
				   				nolinks = false;
					   		}
				   			var altern = feed.getLink("last"); 
				   			if (altern != null) {
				   				navlinks += '<a href="#" onclick="javascript:insertFeed(\''+altern+'\',\''+idInner+'\','+level+');return false;"><img src="image/last.gif" border=0/></a>';
				   				nolinks = false;
					   		}
				   			navlinks += '</span>';
	
				   			if (!nolinks) {
				   				feed.label += navlinks;
				   			}
	
				   			feed.label += '<span class="feedtitle">';
				   			var icon = feed.getLink("icon");
				   			if (icon == null || icon.length == 0) {
				   				var anApp = findApp(service);
				   				if (anApp != null) icon = anApp.icon; 
				   			}
				   			if (icon != null) {
					   			feed.label += '<img border=0 src=\"'+icon+'"/>';
					   		}
				   			feed.label += feed.getTotalResults()+': ';
				   			var altern = feed.getLink("alternate"); 
			   				var feedTitle = feed.getTitle();
			   				if (feedTitle) {
			   					feedTitle = feedTitle.content;
			   					if (!feedTitle) feedTitle = atomClient.service;
			   				}
			   				else {
			   					feedTitle = atomClient.service;
			   				}
				   			if (altern != null) {
					   			feed.label += '<a href="'+altern+'" target="_blank">'+feedTitle+'</a>';
					   		} else if (feed.getTitle()) {
					   			feed.label += feedTitle;
					   		}
				   			feedTitle = feedSize +': '+ feedTitle;
				   			if (feed.getSubtitle()) {
				   				feed.label += ' : <span class="feedsubtitle">'+feed.getSubtitle().content+'</span>';
				   				feedTitle += ': '+feed.getSubtitle().content;
				   			}
				   		    feed.label += '<a href="#" onclick="javascript:alert(\'basket\');return false;" title="Add all results to basket"><img src="image/outbasket.gif" border=0 title="Selection basket"/></a>';
				   			var altern = feed.getLink("via");
				   			if (altern != null) {
				   				feed.label += '<a href="#" onclick="javascript:window.open(\''+altern+'\',\''+atomClient.app+'\').focus();return false;" title="Goto search form?"><img src="image/16x16/search.png" border=0 title="Search Form"/></a>';
				   			}
				   			feed.label += '</span>';
				   		} else { $('#'+idInner+'feedLabel').addClass('emptyfeedtitle'); }
			   			$('#'+idInner+'feedLabel').html(feed.label);

			   			var regNonAlfa = new RegExp('[^a-z0-9]+', 'g');
			   			var lonely = entries.length <= 1;
			   			var records = null;
			   			var indexEntriesLoc = {};
				   		for (var i = 0; i<entries.length; i++) {
				   			var anEntry = entries[i];
			   				anEntry.facets = new Array();
			   				var anUrl = buildIdURL(anEntry.getLink("alternate"));
				   			if (records == null) records="";
				   			else records+='\t';
				   			records += anUrl;
				   			indexEntriesLoc[anUrl] = anEntry;
				   		}

				   		var facetsList = { 'year' : 'Publication:', 'yearUpd' : 'Update:', 'mark' : 'Bookmarks:' };
				   		//alert("/scheme/getcontributions.jsp?application="+application+"&records="+records);
					   	var jsonClient = new AtomClient("/scheme/getcontributions.jsp");
					   	jsonClient.setIndexEntries(indexEntriesLoc);
					   	jsonClient.jsonPost('', "urls="+records, function completeResult( json, client ) {
							//console.log(json);
				   			//alert(json.result.length);
				   			var regNonAlfa = new RegExp('[^a-z0-9]+', 'g');
					   		for (var i = 0; i<json.result.length; i++) {
					   			var aResult = json.result[i];
								if (aResult.display == null) {
									//console.log(i+" = Null IndexEntry with "+json.result[i]+" in "+json+'\n'+serviceURL);
					   				continue;
								}
					   			var anEntry = client.getIndexEntries()[encodeURLnonASCII(encodeURIComponent(aResult.display))];
					   			if (anEntry == null) {
					   				//console.log(i+" = IndexEntry "+aResult.display+' not found\n'+serviceURL);
					   				continue;
					   			}
					   			anEntry.application = aResult.application;
					   			anEntry.record = aResult.record;
					   			anEntry.apprecord = (aResult.application+'-'+aResult.record).replace(regNonAlfa,'-');
					   			anEntry.comments = aResult.comments;
					   			if (aResult.label) {
					   				anEntry.setTitle(aResult.label+': '+anEntry.getTitle().getValue());
					   			}
					   			var categs = aResult.tags;
					   			if (categs != null) {
						   			for (var j = 0; j<categs.length; j++) {
							   			var lab = categs[j].label;
							   			if (lab == null || lab.length == 0) {
							   				lab = categs[j].term; // This to be sure label was not created with new String!
								   			categs[j].label = lab;
							   			}
							   			var catScheme = categs[j].scheme;
							   			if (anEntry[catScheme]) {
							   				var k = anEntry[catScheme].length;
							   				anEntry[catScheme][k] = categs[j];
								   		} else {
								   			anEntry[catScheme] = new Array();
							   				anEntry[catScheme][0] = categs[j];
							   				if (!facetsList[catScheme]) {
							   					var a = findScheme(catScheme);
							   					if (a == null) {
								   					facetsList[catScheme] = catScheme+':';
								   					anEntry.facets[catScheme] = catScheme+':';
							   					} else {
								   					facetsList[catScheme] = (a.icon ? ('<img src="'+a.icon+'" title="'+stringAttribute(a.prefLabel)+'" border=0/>') : '') + a.prefLabel+':';
								   					anEntry.facets[catScheme] = (a.icon ? ('<img src="'+a.icon+'" title="'+stringAttribute(a.prefLabel)+'" border=0/>') : a.prefLabel)+':';
							   					}
							   				}
								   		}
						   			}
						   		}
					   		}
				   		for (var i = 0; i<entries.length; i++) {
				   			var anEntry = entries[i];
				   			var iconEntry = defaultIcon;
				   			var links = anEntry.getLinks();
					   		for (var j = 0; j<links.length; j++) {
				   				if ((links[j].getRelation() == 'icon')) {
				   					iconEntry = links[j].getHRef().getValue();
					   				break;
				   				}
					   		}
		   					iconEntry = '\<img src=\"'+ iconEntry + '\" border=0\/\>';

				   			anEntry.editLink = anEntry.getLink("edit");
				   			if (anEntry.getSource()) {
				   				var sourceLk = anEntry.getSource().getLink("alternate");
				   				if (sourceLk) {
						   			anEntry.sourceLink = new Link(sourceLk,"source");
					   				anEntry.sourceLink.setTitle(anEntry.getSource().getId().getValue());
				   				}
				   			}
			   				anEntry.noSort = i;
				   			var altern = anEntry.getLink("alternate"); 
				   			if (altern != null) {
				   				anEntry.label = anEntry.getTitle();
				   				if (anEntry.label != null) anEntry.label = anEntry.label.content;
				   				if (!anEntry.label) anEntry.label = "--";
				   				anEntry.sortTitle = anEntry.label.toLowerCase().replace(regNonAlfa,'');
					   			anEntry.label = '<a href="#" onclick="javascript:displayOpenLink(this,\''+altern+'\',\''+anEntry.application+'\',\''+idInner+'-'+anEntry.apprecord+'\');return false;">'+iconEntry+anEntry.label+'</a>';
					   		} else {
					   			if (anEntry.getTitle()==null) {
						   			anEntry.label = "***no title***";					   				
					   			} else {
						   			anEntry.label = anEntry.getTitle().content;
					   			}
				   				anEntry.sortTitle = anEntry.label.toLowerCase().replace(regNonAlfa,'');
				   				anEntry.label = iconEntry+anEntry.label;
					   		}
				   			var categs = anEntry.getCategories();
				   			if (categs != null && categs.length > 0) {
						   		for (var j = 0; j<categs.length; j++) {
						   			var lab = categs[j].label;
						   			if (lab == null || lab.length == 0) {
						   				lab = categs[j].term; // This to be sure label was not created with new String!
							   			categs[j].label = lab;
						   			}
						   			var catScheme = categs[j].scheme;
						   			if (anEntry[catScheme]) {
						   				var k = anEntry[catScheme].length;
						   				anEntry[catScheme][k] = categs[j];
							   		} else {
							   			anEntry[catScheme] = new Array();
						   				anEntry[catScheme][0] = categs[j];
					   					var a = findScheme(catScheme);
						   				if (!facetsList[catScheme]) {
						   					if (a == null) {
							   					facetsList[catScheme] = catScheme+':';
						   					} else {
							   					facetsList[catScheme] = (a.icon ? ('<img src="'+a.icon+'" title="'+stringAttribute(a.prefLabel)+'" border=0/>') : '') + a.prefLabel+':';
						   					}
						   				}
					   					if (a == null) {
							   				anEntry.facets[catScheme] = catScheme+':';
					   					} else {
						   					anEntry.facets[catScheme] = (a.icon ? ('<img src="'+a.icon+'" title="'+stringAttribute(a.prefLabel)+'" border=0/>') : a.prefLabel)+':';
					   					}
							   		}
						   		}
				   			}
				   			anEntry.sortPub = anEntry.sortTitle;
				   			anEntry.sortUpd = anEntry.sortTitle;
				   			if (anEntry.getPublished() > 0) {
				   				anEntry.year = new Category (''+(anEntry.getPublished().getFullYear()));
				   				anEntry.month = (''+(anEntry.getPublished().getMonth()+101)).substring(1);
				   				anEntry.sortPub = ''+(9999-anEntry.getPublished().getFullYear())+(99-anEntry.getPublished().getMonth());
				   			} else if (anEntry.getOldPublication()) {
				   				anEntry.year = new Category (anEntry.getOldPublication());
				   				anEntry.month = '';
				   				anEntry.sortPub = ''+(9999-parseInt(anEntry.getOldPublication().substring(0,4)));
				   			} 
				   			if (anEntry.getUpdated() > 0) {
				   				anEntry.monthUpd = (''+(anEntry.getUpdated().getMonth()+101)).substring(1);
				   				anEntry.yearUpd = new Category(''+(anEntry.getUpdated().getFullYear())+'/'+anEntry.monthUpd);
				   				anEntry.sortUpd = ''+(9999-anEntry.getUpdated().getFullYear())+(99-anEntry.getUpdated().getMonth());
				   			}
				   			anEntry.relation = new Array();
				   			linkSeen = '|';
				   			if (links != null && links.length > 0) {
						   		for (var j = 0; j<links.length; j++) {
					   				var lab = links[j].getTitle();
					   				if (lab && lab.length > 0 && (links[j].getRelation().indexOf(':') >= 0)) {
					   					if (links[j].getType().substring(0,16) == 'application/atom') {
					   					  lab = '<a class=\"innerlink\" href=\"#'+idInner+'-'+anEntry.apprecord+'\" onclick="javascript:openInner(this,\''+idInner+'-'+anEntry.apprecord+'\',\''+links[j].getHRef().getValue()+'\','+level+',\''+idInner+'-'+anEntry.apprecord+'\');return false;">'+decoAppRole(links[j].getRelation())+(lab!='1'?(':'+lab):'')+'</a> ';
						   				  var k = anEntry.relation.length;
						   				  anEntry.relation[k] = lab;
						   				  linkSeen = linkSeen+links[j].getRelation()+'|';
					   					}
					   				}
						   		}
						   		for (var j = 0; j<links.length; j++) {
					   				var lab = links[j].getTitle();
					   				if (lab && lab.length > 0 && (links[j].getRelation().indexOf(':') >= 0)) {
					   					if (links[j].getType().substring(0,16) != 'application/atom' && linkSeen.indexOf('|'+links[j].getRelation()+'|') < 0) {
					   					  lab = '<a class="outerlink" href="#" onclick="window.open(\''+links[j].getHRef().getValue()+'\').focus();return false;" target="_blank">'+decoAppRole(links[j].getRelation())+(lab!='1'?lab:'')+'^</a> ';
						   				  var k = anEntry.relation.length;
						   				  anEntry.relation[k] = lab;
					   					}
					   				}
						   		}
				   			}
				   			prevApp = '';
				   		}
				   		
					          var usersettings = { 
					        	idInner : idInner,
					            items              : entries,
					            indexEntries	   : client.getIndexEntries(),
					            baseCount          : feed.getStartIndex()-1,
					            facets             : facetsList, 
					            resultSelector     : '#'+idInner+'results',
					            facetSelector      : '#'+idInner+'facets',
					            facetListSelector  : '#'+idInner+'facetListContainer',
					            bottomSelector	   : '#'+idInner+'bottom',
					            resultTemplate     : '<div class="item lev'+level+'\"><\%=entryDisplay(obj,\"'+idInner+'\",'+level+','+lonely+')%\>'+(lonely?'':('<a href="#'+idInner+'" class="topset"><img src="image/minitop.png" border=0 title="'+stringAttribute(feedTitle)+'"/><\%=obj.itemNr%\></a>'))+'</div>',
					            orderByOptions     : {'showHide':' ',
					            					  'noSort':'<img src="image/sortdown.png" title="Unsorted" border=0/>',
					            					  'sortTitle': '<img src="image/facetsortalfa.png" title="Title" border=0/>',
					            					  'sortPub':'<img src="image/16x16/date.png" title="Publication Date" border=0/><img src="image/sortdown.png" title="Publication Date" border=0/>',
					            					  'sortUpd': '<img src="image/16x16/edit.png" title="Updated" border=0/><img src="image/sortdown.png" title="Updated" border=0/>'},
					            facetContainer     : '<ul id=\"'+idInner+'facetListContainer\" class="yellow2"></ul>',
					            facetTitleTemplate : '<li class="yellow"><a href=\"#'+idInner+'-facethead-\<\%=i\%\>\"><\%= title \%\><\%=count %\></a></li>',
					            facetListContainer : '<div id=\"'+idInner+'-facethead-\<\%=i\%\>\" class="facetsearch"></div>',
					            listItemTemplate   : '<li id=\"'+idInner+'<\%=id \%\>" class=\"facetitem\"><span class=facetitemcount><\%= count \%\></span>: <\%= name \%\> </li>',
					            orderByTemplate    : '<div class=orderby><ul class=orderby><\% _.each(options, function(value, key) { %\>'+
					                                 '<li class=orderbyitem id=\"'+idInner+'orderby_<\%= key %\>\">'+
					                                 '<\%= value %\> </li> <\% }); %\><a class=showalllinks href="#" id="'+idInner+'_showalllinks" onclick="javascript:noHideAll(this,\''+idInner+'\');return false;" title="Show all links">Show links</a></ul></div>',
					            countTemplate      : ' ',//'<div class=facettotalcount><\%= count %\> Results</div>',
					            deselectTemplate   : '<span id=\"'+idInner+'-facetSet"><span class=deselectstartover id=\"'+idInner+'-desel">Deselect all filters</span></span>',
					            noResults          : '<div class=results style="font-weigth:bold;color:red;">NO RESULT</div>',
					            state              : {
					                                   orderBy : (closed?'showHide':'noSort'),
					                                   filters : {}
					                                 },
					            showMoreTemplate   : '<a id='+idInner+'showmorebutton>More</a>',
					            enablePagination   : false,
					            paginationCount  : 1000 // Pagination done by server...
					          };
	
					          // use them!
					          facetters[idInner] = new Facetter(usersettings);
					          if (lonely) {
					        	  $('#'+idInner+'facets').hide();
					        	  $('#'+idInner+'bottom').hide();
					        	  if (closed && entries.length > 0) noHideAll(null,idInner);
					          } else {
					        	  $('#'+idInner+'facets').tabs({ selected: -1 });
					        	  if (closed) {
					        		  $('#'+idInner+'results').hide();
					        	  }
					          }
					          if (closed && entries.length == 0) {
					        	  $('#'+idInner).hide();
					          }
				   		});
			    	} );
   	}
   	
    function openInner(element,idInner,url,level,idRecord) {
		if (idRecord) {
			recClick(idRecord);	
		}
    	if (prevSelElement) {
    		$(prevSelElement).removeClass("ui-tabs-selected ui-state-active");
        	$(prevSelElement).addClass("ui-state-default");
    	}
    	$(element).removeClass("ui-state-default");
    	$(element).addClass("ui-tabs-selected ui-state-active");
    	prevSelElement = element;
		//if (query) query = "?q="+query;
    	insertFeed(url, idInner,level+1);
    	return false;
    }

